package com.dly.blog.service.impl;

import com.dly.blog.domain.config.ChatConfig;
import com.dly.blog.service.ChatClient;
import com.dly.blog.service.ChatConfigService;
import lombok.AllArgsConstructor;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
import reactor.netty.transport.ProxyProvider;

import java.net.InetSocketAddress;

@Service
@AllArgsConstructor
public class ChatClientImpl implements ChatClient {

    private final ChatConfigService chatConfigService;

    private static final WebClient.Builder webClient = WebClient.builder();

    @Override
    public WebClient.Builder getClient() {
        ChatConfig chatConfig = chatConfigService.get();
        return switch (chatConfig.getProxyType()) {
            case PROXY -> {
                webClient.baseUrl(chatConfig.getBaseUrl())
                        .defaultHeader("Authorization", "Bearer " + chatConfig.getKey())
                        .defaultHeader("Content-Type", "application/json")
                        .clientConnector(new ReactorClientHttpConnector(
                                //configure proxy connections
                                HttpClient.create()
                                        .proxy(typeSpec ->
                                                typeSpec.type(ProxyProvider.Proxy.HTTP).address(new InetSocketAddress(chatConfig.getProxyIp(), chatConfig.getPort())))
                        ));
                yield webClient;
            }
            case DIRECT -> {
                webClient.baseUrl(chatConfig.getBaseUrl())
                        .defaultHeader("Authorization", "Bearer " + chatConfig.getKey())
                        .defaultHeader("Content-Type", "application/json");
                yield webClient;
            }
        };
    }

}
